
import { WeApp } from './common/common'
import tools from './common/tools'
import { UserAuth } from './common/auth'
import wxService from './common/wxService'
import { IUser, ILoginUser } from './model/user'
import { Consignee } from './model/consignee';
import { config } from './etc/config';

class WeAppClass implements WeApp {

    public get globalData() {
        return {
            userInfo: null
        }
    }

    public async onLaunch() {
        //调用API从本地缓存中获取数据
        // const logs = wx.getStorageSync('logs') || [];
        // logs.unshift(Date.now());
        // wx.setStorageSync('logs', logs);
       await this.getUserInfo(true);
        setTimeout(() => {
            const sys = wx.getSystemInfoSync();
            wx.setStorageSync(config.storageNames.systemInfo, { system: sys.system });
        }, 1);
    }

    public async getUserInfo(tryAgain?: boolean) {
        if (!tryAgain && UserAuth.checkLogin()) {
            const user = wx.getStorageSync("userInfo");
            return user as IUser;
        } else {
            const loginUser = await UserAuth.Login();
            return loginUser;
        }
    }

    public async addCurUserShopCar(num: number) {
        let user = await this.getUserInfo();
        user.shopCar += num;
        if (user.shopCar < 0) {
            user.shopCar = 0;
        }
        wx.setStorageSync('userInfo', user);
    }

    public setCurUserDefaultConsignee(data: Consignee) {
        let user = wx.getStorageSync("userInfo") as IUser;
        if (!user) {
            return;
        }
        user.consignee = data;
        wx.setStorageSync("userInfo", user);
    }
};

App(new WeAppClass());
